#! /usr/bin/python
#coding=utf-8 
#----PYTHON FOR SIGNATRUE TESTING TOOL----
import sqlite3
import httplib
import socket
import telnetlib
import sys
import time

def usage():
	#"usage massage show"
	print("ax_id.py <DIP> <DPORT> <SQLITE_DB_NAME> <id> <s:c> ]")


def connect_sql_db(dbname):
	print("connect sqlite db name:"+dbname)
	db=sqlite3.connect(dbname)
	return db


def http_request(Dip,Dport,msg):
	try:
		s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	except socket.error as elog:
		s = None
		print("creat socket error!")
		return None
	try:
		int(Dport)
		s.settimeout(5)
		s.connect((Dip,Dport))
	except socket.error as elog:
		s.close()
		s = None
		print("socket connect error !")
		return None
	s.send(msg)
	print(msg)
	try:
		buf = s.recv(8192)
	except socket.error as elog:
		s.close()
		print("socket recving error!")
		s=None
		return None
	s.close()
	print (buf)
	return None


	

def http_packet_send(db,dip,dport,dbid):
	#count =int()
	#id =int(dbid)  
	cur =db.cursor()

	#cur.execute("select payload from log where id= \'60875\'")
	cur.execute("select attack_example from signature_rule where signature_id = \'%s\'"%(dbid))
	
	#print(cur.fetchall())
	for row in cur:
	#	print(str(row[0]))
	#	print("------------------ %s---------------\n"%(row[0]))
		http_request(dip,dport,row[0])

	#printf("count= %d"%(count))
	return 1
	

		



def main(dip,dport,dbname,dbid,ttype):
	#连接sqlite数据库,登陆fortiweb后台
	db = connect_sql_db(dbname)
	
	#time.sleep(5)
	print cmp(ttype, 'c')
	if(cmp(ttype,'c')==0):
		print("\nTesting packet send here!\n")
		ct = http_packet_send(db,dip,dport,dbid)
		print("totle send packet:%d"%(ct))
	else:

	sys.exit()
	




if len(sys.argv) < 5:
	usage()
	sys.exit()

Dip = str(sys.argv[1])
Dport = int(sys.argv[2])
Sql_db = str(sys.argv[3])
dbid = str(sys.argv[4])
ttype = str(sys.argv[5])




if __name__ == "__main__":
	main(Dip,Dport,Sql_db,dbid,ttype)


